//
//  CYPerson.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/23.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYPerson.h"
#import "CYABTool.h"
#import "PinYin5Objc.h"
#import "CYDialTool.h"

@implementation CYPerson

- (NSString *)name {
    if (_name) {
        return _name;
    }
    if (self.person && self.person.name) {
        return self.person.name;
    }
    return self.person.phoneNumbers.values.firstObject;
}

- (NSArray *)phones {
    if (_phones) {
        return _phones;
    }
    NSArray *arr = self.person.phoneNumbers.values;
    if (arr.count) {
        return [CYABTool formatPhoneNumbers:arr];
    }
    return nil;
}

- (NSString *)phone {
    if (_phone) {
        return _phone;
    }
    NSString *rhphone = [self.person.phoneNumbers.values firstObject];
    if (!rhphone) {
        return CYPhoneNameNil;
    }
    return [[CYABTool formatPhoneNumbers:@[rhphone]] firstObject];
}

- (NSInteger)iconType {
    if (self.simpleRecord) {
        return CYIconTypeSX;
    }
    return _iconType;
}

- (void)setPerson:(RHPerson *)person {
    _person = person;
    
    NSString *name = person.name;
    if (!name) {
        name = person.phoneNumbers.values.firstObject;
    }
    _pinyin = [PinYin5Objc chineseConvertToPinYin:name];
    NSString *headerFirst = [PinYin5Objc chineseConvertToPinYinHead:name];
    
    //检查首字母是否是字母
    NSString *regex = @"[a-zA-Z]";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isAlphabet = [predicate evaluateWithObject:headerFirst];
    if (isAlphabet) {
        _pinyinHeaderFirst = headerFirst;
    } else {
        _pinyinHeaderFirst = @"#";
    }
    
    _pinyinHeader = [PinYin5Objc chineseConvertToPinYinHeads:name];
    
    _pinyinIndex = [CYDialTool indexOfpinyin:self.pinyin];
    _pinyinHeaderIndex = [CYDialTool indexOfpinyin:self.pinyinHeader];
}

//- (NSString *)pinyinIndex {
//    return [CYDialTool indexOfpinyin:self.pinyin];
//}

//- (NSString *)pinyinHeaderIndex {
//    return [CYDialTool indexOfpinyin:self.pinyinHeader];
//}

- (instancetype)initWithRHPerson:(RHPerson *)rhPerson {
    self = [super init];
    if (self) {
        self.person = rhPerson;
    }
    return self;
}
@end
